package com.jielihaofeng.atguigu.codec;

import com.jielihaofeng.atguigu.codec2.MyDataInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;
import java.util.Random;

/**
 * @author Johnnie Wind
 * @description Protobuf 客户端
 * @date 2021/11/8 17:42
 */
public class ProtobufClient {

    public static void main(String[] args) throws InterruptedException {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<Channel>() {
                            @Override
                            protected void initChannel(Channel ch) {
                                ChannelPipeline pipeline = ch.pipeline();
                                // 在pipeline中加入编码器 ProtobufEncoder
                                pipeline.addLast(new ProtobufEncoder());
                                pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println("服务端消息：" + msg);
                                    }
                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        // 发送一个Student对象到服务器
                                        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("智多星 无用").build();
                                        ctx.writeAndFlush(student);
                                    }
                                });
                            }
                        })
                .connect("localhost", 8088)
                .sync()
                .channel()
                .writeAndFlush(new Date() + ": hello world!");
    }

}
